package zzps.exeed.kernel.event;

import java.util.HashSet;
import java.util.LinkedHashSet;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 事件广播站
 */
public class EventBroadcaster {

    private static final Map<Class<?>, Set<EventListener>> eventListeners = new ConcurrentHashMap<>(1024);
    private static final Set<EventListener> throwableListeners = new LinkedHashSet<>(1024);
    //广播事件
    public static void broadcaster(Object event){
        if (event instanceof Throwable){
            throwableListeners.stream().forEach(eventListener -> eventListener.onEvent(event));
            return;
        }
        Class<?> aClass = event.getClass();
        Set<EventListener> listeners = eventListeners.get(aClass);
        if (listeners != null){
            listeners.stream().forEach(eventListener -> eventListener.onEvent(event));
        }

    }

    //注册某个事件的监听器
    public static <T> void subscribe(EventListener<T> listener){
        Class<T> eventType = listener.eventType();
        if (Throwable.class.isAssignableFrom(eventType)){
            throwableListeners.add(listener);
            return;
        }
        Set<EventListener> listeners = eventListeners.get(eventType);
        if (listeners == null){
            listeners = new LinkedHashSet<>(1024);
            eventListeners.put(eventType,listeners);
        }
        listeners.add(listener);
    }

    public static <T> void unsubscribe(EventListener<T> listener){
        Class<T> eventType = listener.eventType();
        if (Throwable.class.isAssignableFrom(eventType)){
            throwableListeners.remove(listener);
            return;
        }
        Set<EventListener> listeners = eventListeners.get(eventType);
        if (listeners != null){
            listeners.remove(listener);
        }
    }
}
